package com.itcam.lease.web.admin.service.impl;

import com.itcam.lease.web.admin.service.FileService;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucket-name}")
    private String bucketName;

    @Value("${minio.endpoint}")
    private String endpoint;

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public String upload(MultipartFile file) {

        try {
            // 检查存储桶是否存在
            boolean bucketExists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            // 如果存储桶不存在，则创建存储桶
            if (!bucketExists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
                // 设置存储桶的权限策略，允许所有人读取存储桶中的对象
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(getBucketPolicy(bucketName)).build());
            }

            // 生成对象名称，格式为：日期/UUID-文件名
            String objectName = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            // 上传文件到 MinIO 存储桶
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build());

            // 返回文件的访问路径
            return String.join("/", endpoint, bucketName, objectName);

        } catch (Exception e) {
            // 打印异常堆栈跟踪
            e.printStackTrace();
        }

        // 如果发生异常，返回 null
        return null;
    }

    /**
     * 获取存储桶的权限策略配置
     *
     * @param bucketName 存储桶名称
     * @return 权限策略配置字符串
     */
    private String getBucketPolicy(String bucketName) {
        // 由于公寓、房间的图片为公开信息，所以将其设置为所有人可访问
        // 允许(`Allow`)所有人(`*`)获取(`s3:GetObject`)指定桶(`<bucket-name>`)的内容
        return """
                {
                  "Statement" : [ {
                    "Action" : "s3:GetObject",
                    "Effect" : "Allow",
                    "Principal" : "*",
                    "Resource" : "arn:aws:s3:::%s/*"
                  } ],
                  "Version" : "2012-10-17"
                }
                """.formatted(bucketName);
    }

}
